package com.congee02.springframework.core.io;

import cn.hutool.core.lang.Assert;
import com.congee02.springframework.util.ClassLoaderUtils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * 从 class 根路径读取资源
 * {@link Resource}
 */
public class ClassPathResource implements Resource {

    private final String path;

    private final ClassLoader classLoader;

    public ClassPathResource(String path) {
        this(path, null);
    }

    public ClassPathResource(String path, ClassLoader classLoader) {
        Assert.notNull(path, "Path must be not null");
        this.path = path;
        this.classLoader = (classLoader != null) ? (classLoader) : (ClassLoaderUtils.getDefaultClassLoader());
    }

    @Override
    public InputStream getInputStream() throws IOException {
        InputStream is = classLoader.getResourceAsStream(path);
        if (is == null) {
            throw new FileNotFoundException(this.path + " cannot be opened because it does not exist.");
        }
        return is;
    }

    @Override
    public String toString() {
        return "ClassPathResource{" +
                "path='" + path + '\'' +
                ", classLoader=" + classLoader +
                '}';
    }
}
